/// <reference path="Voucher.js" />
//是否正在切换
var isSwitching = false;
//标记是否需要全选
var allCheck = 0;
//切换凭证的时候存储信息
var switchInfo;
//编辑状态 三种 edit、insert、copy
var EditType = "";
//是否正在编辑
var isEditing = false;
//是否正在取消导入凭证
var isCanceling = false;
//是否正在导入凭证
var isImporting = false;
//凭证对象
var voucherTemplate = null;
//是否有操作凭证的权限
var hasOptionPermission = false;
//选择纸张的边距对象
var marginObj = null;
var isInit = false;

var PrintMargin = {
    A42: { top: 14, left: 25, maxH: 35, maxZ: 29 },
    A43: { top: 5, left: 25, maxH: 35, maxZ: 13 },
    A4Wide: { top: 9, left: 25, maxH: 35, maxZ: 18 },
    Invoice: { top: 9, left: 25, maxH: 35, maxZ: 21 }
}

var GetPageType = function (printType) {
    var result;
    switch (printType) {
        case "1":
            result = PrintMargin.A42;
            break;
        case "2":
            result = PrintMargin.A43;
            break;
        case "3":
            result = PrintMargin.A4Wide;
            break;
        case "4":
            result = PrintMargin.Invoice;
            break;
    }
    return result;
}

$(function () {
    loading("start");
    if ($("#ApproveButton").is(":visible")) {
        $("#noApprovedButton").show();
    }
    else {
        $("#noApprovedButton").hide();
    }

    hasOptionPermission = $("#ImportButton").is(":visible");
    if (!hasOptionPermission) {
        $(".tdTopButton").remove();
    }
    var params = {};
    params.PageNumber = 1;
    params.PageSize = getCookie("VoucherListSize") == null ? "10" : getCookie("VoucherListSize");

    var checkOutP = GetQueryString("CheckOutP");
    if (checkOutP != undefined && checkOutP != null && checkOutP != "") {
        params.StartP = checkOutP;
        params.EndP = checkOutP;
    }

    var unApprove = GetQueryString("unApprove");
    if (unApprove != null && unApprove == "1") {
        allCheck = 2;
        $("#noApproved").attr("checked", true);
        //SearchData();
    }
    params.NoApproved = $("#noApproved").is(":checked") ? "1" : "0";
    Search(params);
    GetIfHasBreakNum(params);
    $('#divPager').pagination({
        total: 0,
        pageSize: getCookie("VoucherListSize") == null ? 10 : parseInt(getCookie("VoucherListSize")),
        onSelectPage: function (pageNumber, pageSize) {
            params.PageNumber = pageNumber;
            params.PageSize = pageSize;
            params.Description = $("#txtDescription").val();
            params.Subject = $("#sbj_value_s input").attr("code");
            params.SubjectCode = $("#sbj_value_s input").attr("code");
            params.StartMoney = $("#txtMoneyStart").val();
            params.EndMoney = $("#txtMoneyEnd").val();
            params.StartP = $("#period_s").val();
            params.EndP = $("#period_e").val();
            params.StartVoucherNo = $("#txtStartVoucherNo").val();
            params.EndVoucherNo = $("#txtEndVoucherNo").val();
            params.NoApproved = $("#noApproved").is(":checked") ? "1" : "0";
            params.VG_ID = $("#selectVoucherGroup").val();
            Search(params);
        }
    });

    $('#divPager2').pagination({
        total: 0,
        pageSize: getCookie("VoucherListSize") == null ? 10 : parseInt(getCookie("VoucherListSize")),
        onSelectPage: function (pageNumber, pageSize) {
            params.PageNumber = pageNumber;
            params.PageSize = pageSize;
            params.Description = $("#txtDescription").val();
            params.Subject = $("#sbj_value_s input").attr("code");
            params.SubjectCode = $("#sbj_value_s input").attr("code");
            params.StartMoney = $("#txtMoneyStart").val();
            params.EndMoney = $("#txtMoneyEnd").val();
            params.StartP = $("#period_s").val();
            params.EndP = $("#period_e").val();
            params.StartVoucherNo = $("#txtStartVoucherNo").val();
            params.EndVoucherNo = $("txtEndVoucherNo").val();
            params.NoApproved = $("#noApproved").is(":checked") ? "1" : "0";
            params.VG_ID = $("#selectVoucherGroup").val();
            Search(params);
        }
    });


    $("#NoteDisplay").bind("mouseover", function () {
        $(this).show();
    });

    $("#NoteDisplay").bind("mouseout", function () {
        $(this).hide();
    });

    $("#CloseDisplayNoteBtn").bind("click", function () {
        $("#NoteDisplay").hide();
    });

    InitSeach(true, false);

    $(".con .jqtransform input[type=text]").css("width", "110px");
    $(".con .jqtransform .jqTransformInputWrapper").css("width", "120px");

    if (getCookie("PrintType") != null) {
        $("input[name=printType]").attr("checked", false);
        $("#rd" + getCookie("PrintType")).attr("checked", true);
    }
    if (getCookie("IsPrintUserName") != null) {
        if (getCookie("IsPrintUserName") == "False") {
            $("#cbxPrintUserName").attr("checked", false);
        }
        else {
            $("#cbxPrintUserName").attr("checked", true);
        }
    }
    if (getCookie("IsPrintApprovedName") != null) {
        if (getCookie("IsPrintApprovedName") == "False") {
            $("#cbxPrintApprovedName").attr("checked", false);
        }
        else {
            $("#cbxPrintApprovedName").attr("checked", true);
        }
    }

    $("#switchLeft").bind("click", function () {
        if ($(this).hasClass("disabledSwitchingLeft")) {
        }
        else {
            if (isSwitching) {
                global_AppMessage("提示", "正在切换，请稍后点击~");
                return;
            }
            isSwitching = true;
            if (EditType == Voucher.LoadType.EditVoucher) {
                InitVoucherUI($("#txtVNum").val(), $("#txtVg_Id").val(), $("#txtPId").val(), "true", "false");
            }
            else {
                InitVoucherUIForNew($("#txtVgId").val(), $("#ddlVoucherGroup").val(), "", $("#txtDate").val(), "true", "false");
            }
        }
    });

    $("#switchRight").bind("click", function () {
        if ($(this).hasClass("disabledSwitchingRight")) {
        }
        else {
            if (isSwitching) {
                global_AppMessage("提示", "正在切换，请稍后点击~");
                return;
            }
            isSwitching = true;
            if (EditType == Voucher.LoadType.EditVoucher) {
                InitVoucherUI($("#txtVNum").val(), $("#txtVg_Id").val(), $("#txtPId").val(), "false", "true");
            }
            else {
                InitVoucherUIForNew($("#txtVgId").val(), $("#ddlVoucherGroup").val(), "", $("#txtDate").val(), "false", "true");
            }
        }
    });

    //setTimeout(function () {
    //    var printVideo = "<a style='width:80px;color:#1EBDDC;margin-top:-2px;margin-right:5px;' href='#'>"
    //        + "<table><tr valign='middle'><td><img src='../Image/010Voucher/vedio.png' /></td><td valign='middle'> 打印视频</td></tr></table>"
    //        + "</a>";
    //    $(printVideo).insertBefore($("#divPrint").prev().find(".panel-tool-close"));
    //}, 300);

    //初始化四个rd的click事件 （打印纸张选择）
    $("input[name=printType]").each(function () {
        var radio = $(this);
        if (radio.attr("checked")) {
            var i = $(this).attr("id").replace("rd", "");
            if (i == "1" || i == "2") {
                $("#rdDirectionZ").attr("checked", true);
                $("input[name=printDirection]").attr("disabled", true);
            }
            else {
                $("#rdDirectionH").attr("checked", true);
                $("input[name=printDirection]").attr("disabled", false);
            }
            marginObj = GetPageType(i);
            $("#txtMarginTop").val(marginObj.top);
            $("#txtMarginBottom").val(marginObj.maxZ - marginObj.top);
            $("#txtMarginLeft").val(marginObj.left);
            $("#txtMarginRight").val(marginObj.maxH - marginObj.left);
        }

        radio.bind("click", function () {
            var i = $(this).attr("id").replace("rd", "");
            if (i == "1" || i == "2") {
                $("#rdDirectionZ").attr("checked", true);
                $("input[name=printDirection]").attr("disabled", true);
            }
            else {
                $("#rdDirectionH").attr("checked", true);
                $("input[name=printDirection]").attr("disabled", false);
            }
            marginObj = GetPageType(i);
            $("#txtMarginTop").val(marginObj.top);
            $("#txtMarginBottom").val(marginObj.maxZ - marginObj.top);
            $("#txtMarginLeft").val(marginObj.left);
            $("#txtMarginRight").val(marginObj.maxH - marginObj.left);
        });
    });

    $("#txtMarginTop").bind("keyup", function () {
        var top = $(this).val();
        if (top == "") {
            top = 0;
        }

        if (isNaN(parseInt(top)) || top.indexOf(".") > -1) {
            ResetMarginZ();
            global_AppMessage("提示", "请输入整数边距~");
        }
        else if (parseInt(top) > marginObj.maxZ) {
            ResetMarginZ();
            global_AppMessage("提示", "最高可设置" + marginObj.maxZ + "边距");
        }
        else {
            var bottom = marginObj.maxZ - parseInt(top);
            $("#txtMarginBottom").val(bottom);
        }
    });

    $("#txtMarginLeft").bind("keyup", function () {
        var left = $(this).val();
        if (left == "") {
            left = 0;
        }
        if (isNaN(parseInt(left)) || left.indexOf(".") > -1) {
            ResetMarginH();
            global_AppMessage("提示", "请输入整数边距~");
        }
        else if (parseInt(left) > marginObj.maxH) {
            ResetMarginH();
            global_AppMessage("提示", "最高可设置" + marginObj.maxH + "边距");
        }
        else {
            var right = marginObj.maxH - parseInt(left);
            $("#txtMarginRight").val(right);
        }
    });
});
//采用正则表达式获取地址栏参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

function fix_select(selector) {
    var i = $(selector).parent().find('div,ul').remove().css('zIndex');
    JQ(selector).removeClass('jqTransformHidden').jqTransSelect();
    $(selector).parent().css('zIndex', i);
}

function OpenSortDialog() {
    $("#divSortVoucherNo").find(".jqTransformSelectWrapper span").width(208);
    $('#divSortVoucherNo').dialog('open');
    $("#selectVgForSort").parent().css("z-index", "");
}

function cancel() {
    if ($(".con").css("display") != "none") {
        $(".con").hide();
    }
}

function SearchData(isDeleteVoucher) {
    if (parseInt($("#period_s").val()) > parseInt($("#period_e").val())) {
        global_AppMessage("提示", "亲，开始日期不能晚于结束日期哟！");
        return;
    }

    var startVoucherNo = $("#txtVoucherNoStart").val();
    var endVoucherNo = $("#txtVoucherNoEnd").val();

    if (startVoucherNo != "" && endVoucherNo != "") {
        if (parseInt(startVoucherNo) > parseInt(endVoucherNo)) {
            global_AppMessage("提示", "开始凭证号不能大于结束凭证号！");
            return;
        }
    }

    var startMoney = $("#txtMoneyStart").val();
    var endMoney = $("#txtMoneyEnd").val();

    if (startMoney != "" && endMoney != "") {
        if (parseFloat(startMoney) > parseFloat(endMoney)) {
            global_AppMessage("提示", "开始金额不能大于结束金额！");
            return;
        }
    }

    if ($("#period_s").val() == $("#period_e").val()) {
        $("#thisperiod").html($("#period_s").find("option:selected").text());
    }
    else {
        $("#thisperiod").html($("#period_s").find("option:selected").text() + "——" + $("#period_e").find("option:selected").text());
    }

    if (isDeleteVoucher) {

    }
    else {
        if (selectedPageNumber != "") {
            $('#divPager').pagination('refresh', { pageNumber: parseInt(selectedPageNumber) });
            $('#divPager2').pagination('refresh', { pageNumber: parseInt(selectedPageNumber) });
            selectedPageNumber = "";
        }
        else {
            $('#divPager').pagination('refresh', { pageNumber: 1 });
            $('#divPager2').pagination('refresh', { pageNumber: 1 });
        }
    }

    var params = {};
    var obj = $('#divPager').pagination("options");
    params.PageNumber = obj.pageNumber;
    params.PageSize = obj.pageSize;
    params.Description = $("#txtDescription").val();
    params.Subject = $("#sbj_value_s input").attr("code");
    params.SubjectCode = $("#sbj_value_s input").attr("code");
    params.StartMoney = $("#txtMoneyStart").val();
    params.EndMoney = $("#txtMoneyEnd").val();
    params.StartP = $("#period_s").val();
    params.EndP = $("#period_e").val();
    params.StartVoucherNo = startVoucherNo;
    params.EndVoucherNo = endVoucherNo;
    params.VG_ID = $("#selectVoucherGroup").val();
    params.NoApproved = $("#noApproved").is(":checked") ? "1" : "0";
    Search(params);
    GetIfHasBreakNum(params);
}

var GetIfHasBreakNum = function (params) {
    var urlCheck = "./false.js";
    $.post(urlCheck, params, function (result) {
        if (result.result == "True") {
            global_AppMessage("提示", "亲，您选择的期间凭证有断号！");
        }
    }, "json");
}

function reset() {
    $("#sbj_value_s").find("div input").val("");
    $("#sbj_value_s").find("div input").attr("code", "");

    $("#txtDescription").val("");
    $("#txtMoneyStart").val("");
    $("#txtMoneyEnd").val("");
    $("#txtVoucherNoStart").val("");
    $("#txtVoucherNoEnd").val("");
}

function Search(params) {
    var url = "./list.js";
    $.post(url, params, function (result) {
        InitTables(result);
        resizeFrameHeight($("#divMain").height());
        setCookie("VoucherListSize", params.PageSize);
        $('#divPager').pagination('refresh', { total: parseInt(result.vouchertotal), pageNumber: params.PageNumber, pageSize: params.PageSize });
        $('#divPager2').pagination('refresh', { total: parseInt(result.vouchertotal), pageNumber: params.PageNumber, pageSize: params.PageSize });
        if (parseInt(result.vouchertotal) == 0) {
            $('#divHidPager').hide();
        }
        else {
            $('#divHidPager').show();
        }
        loading("stop");
        ScrollTop();
        $(".con").hide();
        $("#CheckAll").attr("checked", false);
        if (allCheck > 0) {
            $("#divVoucherList").find('input:checkbox').each(function () {
                $(this).attr("checked", true);
            })
            allCheck = allCheck - 1;
        }
    }, "json");
}

function EditOver(isDelete) {
    $(".masterTopTitle span").html("凭证列表");
    InitSeach(false, isDelete);
}

var selectedStartP = "";
var selectedEndP = "";
var selectedPageNumber = "";

function InitSeach(isFirst, isDelete) {
    var sortP = $("#ddlSortPeroid").val();
    $.ajax({
        type: "post",
        url: "./false.js",
        data: { handertype: "getperiod", AS_ID: $("#txtAS_ID").val() },
        dataType: "text",
        success: function (data) {
            if (data != "") {
                $("#period_s").html(data);
                $("#period_e").html(data);
                $("#ddlSortPeroid").html(data);

                if (sortP != undefined) {
                    $("#ddlSortPeroid").val(sortP);
                }
                if (isFirst) {
                    var checkOutP = GetQueryString("CheckOutP");
                    if (checkOutP != undefined && checkOutP != null && checkOutP != "") {
                        $("#period_s").val(checkOutP);
                        $("#period_e").val(checkOutP);
                        $("#ddlSortPeroid").val(checkOutP);
                    }
                }
                else {
                    if (selectedStartP != "" && $("#period_s").find("option[value=" + selectedStartP + "]").length > 0) {
                        $("#period_s").val(selectedStartP);
                        selectedStartP = "";
                    }
                    else {
                        $("#period_s").get(0).selectedIndex = 0;
                    }
                    if (selectedEndP != "" && $("#period_e").find("option[value=" + selectedEndP + "]").length > 0) {
                        $("#period_e").val(selectedEndP);
                        selectedEndP = "";
                    }
                    else {
                        $("#period_e").get(0).selectedIndex = 0;
                    }
                }

                if ($("#period_s").val() == $("#period_e").val()) {
                    $("#thisperiod").html($("#period_s").find("option:selected").text());
                }
                else {
                    $("#thisperiod").html($("#period_s").find("option:selected").text() + "——" + $("#period_e").find("option:selected").text());
                }
                if (!isFirst) {
                    SearchData(isDelete);
                }
            }
            else {
                $("#thisperiod").html("—暂无数据—");
                $("#period_s").html("<option value=''>请选择</option>");
                $("#period_e").html("<option value=''>请选择</option>");
                InitGrid('');
            }

            fix_select("#period_s");
            fix_select("#period_e");
            fix_select("#ddlSortPeroid");
            $(".con .jqTransformSelectWrapper").css("width", "120px");
            $(".con .jqTransformSelectWrapper span").css("width", "120px");
            $(".con .jqTransformSelectWrapper ul").css("width", "120px");
        }
    });
    $.ajax({
        type: "post",
        url: "./false.js",
        data: { handertype: "currencytype", AS_ID: $("#txtAS_ID").val() },
        dataType: "text",
        success: function (data) {
            $("#CurencyType").html(data);
            fix_select("#CurencyType");
        }
    });

    $("#selectVoucherGroup").parents(".jqTransformSelectWrapper").css("z-index", "");
    global_loadTopAccounstInfo();
}

var GetOptionButton = function (buttonType, voucher) {
    var resultButton = "";

    switch (buttonType) {
        case "Edit":
            {
                if (hasOptionPermission) {
                    resultButton += "<div class='optionButtonContainer'>";
                }
                else {
                    resultButton += "<div class='optionButtonContainer' style='display:none;'>";
                }
                if (voucher.STATUS == "3" || voucher.APPROVE_STATUS == "1" || ((voucher.V_TYPE == "220" || voucher.V_TYPE == "210") && voucher.FA_STATUS == "3")) {
                    resultButton += "<a class='optionButton' onclick='Edit(\"" + voucher.V_ID + "\",\"" + voucher.P_ID + "\")'><span class='optionButtonEdit'></span>查看</a>&nbsp;&nbsp;";
                }
                else {
                    resultButton += "<a class='optionButton' onclick='Edit(\"" + voucher.V_ID + "\",\"" + voucher.P_ID + "\")'><span class='optionButtonEdit'></span>修改</a>&nbsp;&nbsp;";
                }
                break;
            }
        case "Copy":
            {
                if (hasOptionPermission) {
                    resultButton += "<div class='optionButtonContainer'>";
                }
                else {
                    resultButton += "<div class='optionButtonContainer' style='display:none;'>";
                }
                resultButton += "<a class='optionButton' onclick='Copy(\"" + voucher.V_ID + "\",\"" + voucher.P_ID + "\")'><span class='optionButtonCopy'></span>复制</a>&nbsp;&nbsp;";
                break;
            }
        case "Delete":
            {
                if (hasOptionPermission) {
                    resultButton += "<div class='optionButtonContainer'>";
                }
                else {
                    resultButton += "<div class='optionButtonContainer' style='display:none;'>";
                }
                if (voucher.STATUS == "3" || voucher.APPROVE_STATUS == "1" || ((voucher.V_TYPE == "220" || voucher.V_TYPE == "210") && voucher.FA_STATUS == "3")) {
                    resultButton += "<a class='optionButton' onclick='global_AppMessage(\"提示\",\"亲，已审核、已结账或者固定资产模块结账期间的固定资产凭证不能删除！\")'><span class='optionButtonDelete'></span>删除</a>&nbsp;&nbsp;";
                }
                else {
                    resultButton += "<a class='optionButton' onclick='Delete(\"" + voucher.V_ID + "\",\"" + voucher.P_ID + "\",\"DeleteVoucher\")'><span class='optionButtonDelete'></span>删除</a>&nbsp;&nbsp;";
                }
                break;
            }
        case "Insert":
            {
                if (hasOptionPermission) {
                    resultButton += "<div class='optionButtonContainer'>";
                }
                else {
                    resultButton += "<div class='optionButtonContainer' style='display:none;'>";
                }
                resultButton += "<a class='optionButton' onclick='Insert(\"" + voucher.V_ID + "\",\"" + voucher.P_ID + "\")'><span class='optionButtonInsert'></span>插入</a>&nbsp;&nbsp;";
                break;
            }
        case "Print":
            {
                resultButton += "<div class='optionButtonContainer'>";
                resultButton += "<a class='optionButton' onclick=\"PrintSelectedItem('" + voucher.V_ID + "','" + voucher.P_ID + "')\"><span class='optionButtonPrint'></span>打印</a>";
                break;
            }
        case "Note":
            {
                resultButton += "<div class='optionButtonContainer'>";
                if (voucher.NOTE == "") {
                    resultButton += "<a id='imgNote" + voucher.P_ID + voucher.V_ID + "' class='optionButton'><span class='optionButtonNote'></span>备注</a>";
                }
                else {
                    resultButton += "<a id='imgNote" + voucher.P_ID + voucher.V_ID + "' class='optionButton'><span class='optionButtonNote'></span>备注</a>";
                }
            }
    }
    resultButton += "</div>";
    return resultButton;
}

function InitTables(obj) {
    $("#divVoucherList").html("");
    for (var i = 0; i < obj.vouchers.length; i++) {
        var voucher = obj.vouchers[i];
        var tableHtml = "<div class='VoucherTables'><div class='VoucherHeader'>"
                                        + "<div class='VoucherCheck'>"
                                        + "<input type='checkbox' id = '" + voucher.V_ID + "' pid = '" + voucher.P_ID + "'/>"
                                        + "</div>"
                                        + "<div class='VoucherTitle'>日期:" + voucher.V_DATE.replace("0:00:00", "")
                                        + "&nbsp;&nbsp;&nbsp;凭证字号：" + voucher.VG_NAME + "-" + voucher.V_NUM + "</div>"
                                        + "<div class = 'VoucherApproved'>"
                                        + "<span id='imgApprove" + voucher.P_ID + voucher.V_ID + "' title='已审核' ></span>"
                                        + "</div>"
                                        + "<div class = 'VoucherNote'>"
                                        + GetOptionButton("Note", voucher)
                                        + "<input type ='text' style='display:none;' id = 'txt" + voucher.P_ID + voucher.V_ID + "' />"
                                        + "</div>"
                                        + "<div class='VoucherOptions'>"
                                        + GetOptionButton("Edit", voucher)
                                        + GetOptionButton("Copy", voucher)
                                        + GetOptionButton("Delete", voucher)
                                        + GetOptionButton("Insert", voucher)
                                        + GetOptionButton("Print", voucher)
                                        + "</div>"
                                        + "</div>"
                                        + "<table class='userTable' cellspacing='0' id='tb" + voucher.P_ID + voucher.V_ID + "'></table></div>";
        $("#divVoucherList").append(tableHtml);
        if (voucher.APPROVE_STATUS == "0") {
            $("#imgApprove" + voucher.P_ID + voucher.V_ID).hide();
        }
        $("#txt" + voucher.P_ID + voucher.V_ID).val(voucher.NOTE);
        if (voucher.NOTE == "") {
            $("#imgNote" + voucher.P_ID + voucher.V_ID).hide();
        }
        else {
            $("#imgNote" + voucher.P_ID + voucher.V_ID).bind("mouseover", function () {
                var currentOffset = $(this).offset();
                $("#txtVoucherNoteDisplay").val($("#txt" + $(this).attr("id").replace("imgNote", "")).val());
                $("#NoteDisplay").show().offset({ top: currentOffset.top + 16, left: currentOffset.left - 140 });
            });

            $("#imgNote" + voucher.P_ID + voucher.V_ID).bind("mouseout", function () {
                $("#NoteDisplay").hide();
            });
        }

        GetGrid("tb" + voucher.P_ID + voucher.V_ID, voucher.voucherline);
        $("#divMain").height($("#divInfo").height());
    }
}

function getdata(sbj_id) {
    params.PageNumber = $('#pp').pagination("pageNumber");
    params.PageSize = $('#pp').pagination("pageSize");
    params.Description = $("#txtDescription").val();
    params.Subject = $("#sbj_value_s input").attr("code");
    params.SubjectCode = $("#sbj_value_s input").attr("code");
    params.StartMoney = $("#txtMoneyStart").val();
    params.EndMoney = $("#txtMoneyEnd").val();

    var query = {
        AS_ID: $("#txtAS_ID").val(),
        period_s: $("#period_s").val(),
        period_e: $("#period_e").val(),
        sbj_id: sbj_id
    };

    $("#tblist").datagrid('options').queryParams = query;
    $("#tblist").datagrid('reload');
    $("#thisperiod").html($("#period_s").find("option:selected").text() + "——" + $("#period_e").find("option:selected").text())
}

function ApproveVouchers() {
    var checkBoxList = $("#divVoucherList").find(".VoucherCheck input[type=checkbox]:checked");
    if (checkBoxList.length > 0) {
        global_ConfirmDialog('提示', '亲，确认要审核吗？', function (r) {
            if (r) {
                var voucherIds = "";
                var voucherPIds = "";
                for (var i = 0; i < checkBoxList.length; i++) {
                    if (voucherIds.length > 0) {
                        voucherIds += "," + $(checkBoxList[i]).attr("id");
                        voucherPIds += "," + $(checkBoxList[i]).attr("pid");
                    }
                    else {
                        voucherIds += $(checkBoxList[i]).attr("id");
                        voucherPIds += $(checkBoxList[i]).attr("pid");
                    }
                }

                var apprvoveUrl = "Services/ApproveVouchers.ashx";
                $.post(apprvoveUrl, { VoucherList: voucherIds, PList: voucherPIds }, function (result) {
                    if (result != undefined) {
                        global_AlertDialog('提示', "成功：" + result.SUCCESS + "，跳过：" + result.JUMP + "（已经审核的凭证或者已经结账的凭证，将会被跳过！）", 'info');
                        SearchData(false);
                    }
                    else {
                        global_AppMessage("提示", "亲，审核失败啦！请联系系统管理员！");
                    }
                }, "json");
            }
        });
    }
    else {
        global_AppMessage("提示", "亲，您还没有选择凭证哦！");
    }
}

function CancelApproveVouchers() {
    var checkBoxList = $("#divVoucherList").find(".VoucherCheck input[type=checkbox]:checked");
    if (checkBoxList.length > 0) {
        global_ConfirmDialog('提示', '亲，确认要取消审核吗？', function (r) {
            //        top.ConfirmDialog('提示', '亲，确认要取消审核吗?', function (r) {
            if (r) {
                var voucherIds = "";
                var voucherPIds = "";
                for (var i = 0; i < checkBoxList.length; i++) {
                    if (voucherIds.length > 0) {
                        voucherIds += "," + $(checkBoxList[i]).attr("id");
                        voucherPIds += "," + $(checkBoxList[i]).attr("pid");
                    }
                    else {
                        voucherIds += $(checkBoxList[i]).attr("id");
                        voucherPIds += $(checkBoxList[i]).attr("pid");
                    }
                }

                var apprvoveUrl = "Services/CancelApproveVouchers.ashx";
                $.post(apprvoveUrl, { VoucherList: voucherIds, PList: voucherPIds }, function (result) {
                    if (result != undefined) {
                        global_AlertDialog('提示', "成功：" + result.SUCCESS + "，跳过：" + result.JUMP + "（没有审核的凭证或者已经结账的凭证，将会被跳过！）", 'info');
                        SearchData(false);
                    }
                    else {
                        global_AlertDialog("提示", "亲，取消失败啦！请联系系统管理员！");
                    }
                }, "json");
            }
        });
    }
    else {
        global_AppMessage("提示", "亲，您还没有选择凭证哦！");
    }
}

function DeleteVouchers() {
    var checkBoxList = $("#divVoucherList").find(".VoucherCheck input[type=checkbox]:checked");
    if (checkBoxList.length > 0) {
        global_ConfirmDialog('提示', '亲，确认要删除凭证吗？', function (r) {
            if (r) {
                var voucherIds = "";
                var voucherPIds = "";
                for (var i = 0; i < checkBoxList.length; i++) {
                    if (voucherIds.length > 0) {
                        voucherIds += "," + $(checkBoxList[i]).attr("id");
                        voucherPIds += "," + $(checkBoxList[i]).attr("pid");
                    }
                    else {
                        voucherIds += $(checkBoxList[i]).attr("id");
                        voucherPIds += $(checkBoxList[i]).attr("pid");
                    }
                }

                var deleteUrl = "Services/DeleteVouchers.ashx";
                $.post(deleteUrl, { VoucherList: voucherIds, PList: voucherPIds }, function (result) {
                    if (result != undefined) {
                        global_AlertDialog('提示', "成功：" + result.SUCCESS + "，跳过：" + result.JUMP + "（已经审核、已经结账或固定资产的凭证，将会被跳过！）", 'info');
                        EditOver(true);
                    }
                    else {
                        global_AppMessage("提示", "亲，删除失败啦！请联系系统管理员！");
                    }
                }, "json");
            }
        });
    }
    else {
        global_AppMessage("提示", "亲，您还没有选择凭证哦！");
    }
}

function GetGrid(tableId, data) {
    var totalDebit = GetSumData(data, "DEBIT");
    var totalCredit = GetSumData(data, "CREDIT");
    var footers = [];
    var footer = {
        DESCRIPTION: "合&nbsp;&nbsp;计",
        ASUB_NAME: digitUppercase(totalCredit),
        DEBIT: toDecimal2(totalDebit),
        CREDIT: toDecimal2(totalCredit)
    };
    data.push(footer);

    var tableStr = "";
    for (var rowcount = 0; rowcount < data.length; rowcount++) {
        var debitFormat = FormatNumber(toDecimal2(data[rowcount].DEBIT));
        var creditFormat = FormatNumber(toDecimal2(data[rowcount].CREDIT));
        if (debitFormat == "0.00")
            debitFormat = "";
        if (creditFormat == "0.00")
            creditFormat = "";

        var fcInfo = "";
        //if (data[rowcount].FOREIGNCURRENCY == "1") {
        //    var fc_Amount = parseFloat(data[rowcount].FC_AMOUNT).toString().indexOf('.') > -1 && parseFloat(data[rowcount].FC_AMOUNT).toString().split('.')[1].length > 2 ? parseFloat(data[rowcount].FC_AMOUNT).toFixed(2) : parseFloat(data[rowcount].FC_AMOUNT);
        //    var fc_Rate = parseFloat(data[rowcount].FC_RATE).toString().indexOf('.') > -1 && parseFloat(data[rowcount].FC_RATE).toString().split('.')[1].length > 5 ? parseFloat(data[rowcount].FC_RATE).toFixed(5) : parseFloat(data[rowcount].FC_RATE)
        //    fcInfo += "（" + data[rowcount].FC_CODE + ":" + fc_Amount + "，汇率:" + fc_Rate + "）";
        //}
        var className = rowcount % 2 == 0 ? "oddrow" : "evenrow";
        var rowStr = "<tr class='" + className + "'>";
        rowStr += "<td class='tdDescription'>" + data[rowcount].DESCRIPTION + fcInfo + "</td>";
        rowStr += "<td class='tdAsubName'>" + data[rowcount].ASUB_NAME + "</td>";
        rowStr += "<td class='tdDebit'>" + debitFormat + "</td>";
        rowStr += "<td class='tdCredit'>" + creditFormat + "</td>";
        rowStr += "</tr>";
        tableStr += rowStr;
    }
    $("#" + tableId).html(tableStr);
}

var GetSumData = function (data, columnName) {
    var result = 0;
    for (var i = 0; i < data.length; i++) {
        if (columnName == "DEBIT") {
            result += parseFloat(data[i].DEBIT);
        }
        else {
            result += parseFloat(data[i].CREDIT);
        }
    }
    return result;
}

$(function () {
    document.onkeydown = function (e) {
        e = e || window.event;
        kc = e.keyCode || e.charCode;
        if ((kc == 83 && e.ctrlKey)) {
            //ctrl + S 保存
            Save();
            return false;
        }
        else if (kc == 123) {
            //F12 保存并新增
            Save();
            return false;
        }
    }

    $(".VoucherTables").live("mouseover", function () {
        $(this).find(".VoucherCheck input").show();
        $(this).find(".VoucherOptions").show();
        $(this).css("border", "1px solid rgb(99,191,92)");
    });
    $(".VoucherTables").live("mouseout", function () {
        if ($(this).find("input").attr("checked")) {
            $(this).find(".VoucherCheck input").show();
        }
        else {
            $(this).find(".VoucherCheck input").hide();
        }
        $(this).find(".VoucherOptions").hide();
        $(this).css("border", "1px solid silver");
    });

    voucherTemplate = new Voucher("#createVoucherTemplate", null, false, function () {
        isEditing = true;
        ChangeButtonStatus();
    }, false, function () {
        if (isInit) {
            $("#divMain").height($("#divEdit").height());
            resizeFrameHeight($("#divMain").height());
        }
    }, "#spVgTitle");
    voucherTemplate.LoadVoucher(Voucher.LoadType.NewVoucher, { IsFirst: true }, function () { isInit = true; }, voucherTemplate);

    $('#divPrint').dialog({
        title: "凭证打印&nbsp;&nbsp;<a href='http://www.ningmengyun.com/Open/Play.aspx?vt=1002&set=10' target='view_window' style='color:rgb(30,189,220);font-size:10.5px;'>不会操作？点此观看视频</a>",
        width: 400,
        height: 430,
        closed: true,
        cache: false,
        modal: true
    });

    $('#divExport').dialog({
        title: "凭证导出",
        width: 400,
        height: 200,
        closed: true,
        cache: false,
        modal: true
    });

    $('#divSortVoucherNo').dialog({
        title: "整理断号",
        width: 400,
        height: 280,
        closed: true,
        cache: false,
        modal: true
    });

    $("#CheckAll").click(function () {
        if ($("#CheckAll").attr("checked")) {
            $(".VoucherCheck").find("input[type=checkbox]").attr("checked", true).show();
        }
        else {
            $(".VoucherCheck").find("input[type=checkbox]").attr("checked", false).hide();
        }
    });

    $(".VoucherCheck").find("input[type=checkbox]").live("click", function () {
        if ($(this).attr("checked")) {

        }
        else {
            $("#CheckAll").attr("checked", false);
        }
    });

});

function Edit(vId, pId) {
    EditVoucher(vId, pId, false)
}

function EditVoucher(vId, pId, isSwitch) {
    EditType = Voucher.LoadType.EditVoucher;
    $("#txtVId").val(vId);
    $("#txtPId").val(pId);
    var param = { V_ID: vId, P_ID: pId };
    voucherTemplate.LoadVoucher("EditVoucher", param, function (callBackObj) {
        $("#txtVg_Id").val($("#ddlVoucherGroup").val());
        var vNum = $("#txtVgId").val();
        $("#txtVNum").val(vNum);
        var vgId = $("#txtVg_Id").val();
        if (!isSwitch) {
            InitVoucherUI(vNum, vgId, pId, "false", "false");
        }
        if (callBackObj.IsReadOnly) {
            $("#btnSaveVoucher").hide();
            $("#btnDeleteVoucher").hide();
            $("#btnCancelVoucher").hide();
            $("#btnBackVoucher").show();
        }
        else {
            $("#btnSaveVoucher").show();
            $("#btnDeleteVoucher").show();
            $("#btnCancelVoucher").show();
            $("#btnBackVoucher").hide();
        }
        ScrollTop();
        isSwitching = false;
        isEditing = false;
        ChangeButtonStatus();
    }, voucherTemplate);
    OverFlow("divInfo", "divEdit");

    setTimeout(function () {
        resizeFrameHeight($("#divMain").height());
    }, 650);
}

function Copy(vId, pId) {
    EditType = Voucher.LoadType.CopyVoucher;
    selectedStartP = $("#period_s").val();
    selectedEndP = $("#period_e").val();
    selectedPageNumber = $('#divPager').pagination("options").pageNumber;
    var param = { V_ID: vId, P_ID: pId };
    voucherTemplate.LoadVoucher("CopyVoucher", param, function (callBackObj) {
        $("#btnSaveVoucher").show();
        $("#btnCancelVoucher").show();
        $("#btnDeleteVoucher").show();
        $("#btnBackVoucher").hide();
        ScrollTop();
        $("#txtVg_Id").val($("#ddlVoucherGroup").val());
        InitVoucherUIForNew($("#txtVgId").val(), $("#ddlVoucherGroup").val(), "", $("#txtDate").val(), "false", "false");
        isSwitching = false;
        isEditing = true;
        ChangeButtonStatus();
    }, voucherTemplate);
    OverFlow("divInfo", "divEdit");
    setTimeout(function () {
        resizeFrameHeight($("#divMain").height());
    }, 650);
    $(".masterTopTitle span").html("记账凭证");
}

function Insert(vId, pId) {
    EditType = Voucher.LoadType.InsertVoucher;
    selectedStartP = $("#period_s").val();
    selectedEndP = $("#period_e").val();
    selectedPageNumber = $('#divPager').pagination("options").pageNumber;
    var param = { V_ID: vId, P_ID: pId };
    voucherTemplate.LoadVoucher(Voucher.LoadType.InsertVoucher, param, function () {
        $("#btnSaveVoucher").show();
        $("#btnCancelVoucher").show();
        $("#btnDeleteVoucher").show();
        $("#btnBackVoucher").hide();
        $("#txtVg_Id").val($("#ddlVoucherGroup").val());
        InitVoucherUIForNew($("#txtVgId").val(), $("#ddlVoucherGroup").val(), "", $("#txtDate").val(), "false", "false");
        isSwitching = false;
        isEditing = false;
        ChangeButtonStatus();
    }, voucherTemplate);
    OverFlow("divInfo", "divEdit");
    setTimeout(function () {
        resizeFrameHeight($("#divMain").height());
    }, 650);
    $(".masterTopTitle span").html("记账凭证");
}

function Cancel() {
    CancelFlow("divInfo", "divEdit");
    $(".masterTopTitle span").html("凭证列表");
    setTimeout(function () {
        resizeFrameHeight($("#divMain").height());
    }, 650);
}

function Delete(vId, pId, deleteType) {
    global_ConfirmDialog('提示', '亲，确认要删除吗？', function (r) {
        if (r) {
            selectedStartP = $("#period_s").val();
            selectedEndP = $("#period_e").val();
            selectedPageNumber = $('#divPager').pagination("options").pageNumber;

            var param = { V_ID: vId, P_ID: pId };
            Voucher.DeleteVoucher(param, deleteType, function (result) {
                if (result) {
                    EditOver(true);
                    $('#divImport').dialog('close');
                    global_AppMessage("提示", "亲，删除成功啦！");
                }
                else {
                    global_AppMessage("提示", "亲，删除失败啦！联系系统管理员吧！");
                }
            });
        }
    });
}

function DeleteVoucher() {
    if (!$("#btnDeleteVoucher a").hasClass("button")) {
        return;
    }
    var vId = $("#txtVId").val();
    var pId = $("#txtPId").val();
    var deleteType = "DeleteVoucher";

    global_ConfirmDialog('提示', '亲，确认要删除吗？', function (r) {
        if (r) {
            selectedStartP = $("#period_s").val();
            selectedEndP = $("#period_e").val();
            selectedPageNumber = $('#divPager').pagination("options").pageNumber;

            var param = { V_ID: vId, P_ID: pId };
            Voucher.DeleteVoucher(param, deleteType, function (result) {
                if (result) {
                    if (switchInfo.HasNext) {
                        $("#switchRight").click();
                        InitSeach(false, true);
                    }
                    else if (switchInfo.HasPrev) {
                        $("#switchLeft").click();
                        InitSeach(false, true);
                    }
                    else {
                        EditOver(true);
                        CancelFlow("divInfo", "divEdit");
                    }
                    global_AppMessage("提示", "亲，删除成功啦！");
                }
                else {
                    global_AppMessage("提示", "亲，删除失败啦！联系系统管理员吧！");
                }
            });
        }
    });
}

function Save() {
    if (!$("#btnSaveVoucher a").hasClass("button")) {
        return;
    }
    selectedStartP = $("#period_s").val();
    selectedEndP = $("#period_e").val();
    selectedPageNumber = $('#divPager').pagination("options").pageNumber;
    voucherTemplate.SaveVoucher(function (resultObj, result) {
        if (result) {
            global_AppMessage("提示", "亲，保存成功啦！");
            EditOver(false);
            isEditing = false;
            EditType = Voucher.LoadType.EditVoucher;
            $("#txtVId").val(resultObj.V_ID);
            $("#txtPId").val(resultObj.P_ID);
            ChangeButtonStatus();
        }
        else {
            if (resultObj.ERROR != "") {
                global_AppMessage("提示", resultObj.ERROR);
            }
            else if (resultObj.ERROR != "Cancel") {
                global_AppMessage("提示", "亲，保存失败啦！联系系统管理员吧！");
            }
        }
    });
}

var Print = function () {
    var printVoucherCountType = $("input[name=PrintVoucherCountType]:checked").attr("id").replace("rd", "");
    var params = {};
    params.PrintVoucherCountType = printVoucherCountType;
    if (printVoucherCountType == "PrintAll") {
        var obj = $('#divPager').pagination("options");

        params.PageNumber = obj.pageNumber;
        params.PageSize = obj.pageSize;
        params.Description = $("#txtDescription").val();
        params.Subject = $("#sbj_value_s input").attr("code");
        params.SubjectCode = $("#sbj_value_s input").attr("code");
        params.StartMoney = $("#txtMoneyStart").val();
        params.EndMoney = $("#txtMoneyEnd").val();
        params.StartP = $("#period_s").val();
        params.EndP = $("#period_e").val();

        var startVoucherNo = $("#txtVoucherNoStart").val();
        var endVoucherNo = $("#txtVoucherNoEnd").val();
        params.StartVoucherNo = startVoucherNo;
        params.EndVoucherNo = endVoucherNo;
        params.NoApproved = $("#noApproved").is(":checked") ? "1" : "0";
        params.VG_ID = $("#selectVoucherGroup").val();

        var printType = $("input[name=printType]:checked").attr("id").replace("rd", "");
        var printDirection = $("input[name=printDirection]:checked").attr("id").replace("rdDirection", "");

        params.PrintType = printType;
        params.Direction = printDirection;
        params.IsPrintUserName = $("#cbxPrintUserName").attr("checked") ? "True" : "False";
        params.IsPrintApprovedName = $("#cbxPrintApprovedName").attr("checked") ? "True" : "False";
        params.IsPrintFrontCover = $("#cbxPrintFrontCover").attr("checked") ? "True" : "False";

        setCookie("PrintType", printType);
        setCookie("IsPrintUserName", params.IsPrintUserName);
        setCookie("IsPrintApprovedName", params.IsPrintApprovedName);

        PrintAllVoucher(params, "凭证打印");
    }
    else {
        PrintSelectedItem();
    }
}

var OpenExportDialog = function () {
    $('#divExport').dialog('open');
}

var Export = function () {
    var exportVoucherCountType = $("input[name=ExportVoucherCountType]:checked").attr("id").replace("rd", "");
    if (exportVoucherCountType == "ExportAll") {
        var params = {};
        var obj = $('#divPager').pagination("options");
        params.PageNumber = obj.pageNumber;
        params.PageSize = obj.pageSize;
        params.Description = $("#txtDescription").val();
        params.Subject = $("#sbj_value_s input").attr("code");
        params.SubjectCode = $("#sbj_value_s input").attr("code");
        params.StartMoney = $("#txtMoneyStart").val();
        params.EndMoney = $("#txtMoneyEnd").val();
        params.StartP = $("#period_s").val();
        params.EndP = $("#period_e").val();
        params.NoApproved = $("#noApproved").is(":checked") ? "1" : "0";
        params.VG_ID = $("#selectVoucherGroup").val();

        var startVoucherNo = $("#txtVoucherNoStart").val();
        var endVoucherNo = $("#txtVoucherNoEnd").val();
        params.StartVoucherNo = startVoucherNo;
        params.EndVoucherNo = endVoucherNo;

        var tempForm = document.createElement("form");
        tempForm.id = "tempForm1";
        tempForm.method = "post";
        tempForm.action = "Services/ExportVoucher.ashx";
        tempForm.target = name;

        var hideInput1 = document.createElement("input");
        hideInput1.type = "hidden";
        hideInput1.name = "PageNumber"
        hideInput1.value = params.PageNumber;
        tempForm.appendChild(hideInput1);

        var hideInput2 = document.createElement("input");
        hideInput2.type = "hidden";
        hideInput2.name = "PageSize"
        hideInput2.value = params.PageSize;
        tempForm.appendChild(hideInput2);

        var hideInput3 = document.createElement("input");
        hideInput3.type = "hidden";
        hideInput3.name = "AsId"
        hideInput3.value = $("#txtAS_ID").val();
        tempForm.appendChild(hideInput3);

        var hideInput4 = document.createElement("input");
        hideInput4.type = "hidden";
        hideInput4.name = "Description"
        hideInput4.value = params.Description;
        tempForm.appendChild(hideInput4);

        var hideInput5 = document.createElement("input");
        hideInput5.type = "hidden";
        hideInput5.name = "Subject"
        hideInput5.value = params.Subject;
        tempForm.appendChild(hideInput5);

        var hideInput6 = document.createElement("input");
        hideInput6.type = "hidden";
        hideInput6.name = "SubjectCode"
        hideInput6.value = params.SubjectCode;
        tempForm.appendChild(hideInput6);

        var hideInput7 = document.createElement("input");
        hideInput7.type = "hidden";
        hideInput7.name = "StartMoney"
        hideInput7.value = params.StartMoney;
        tempForm.appendChild(hideInput7);

        var hideInput8 = document.createElement("input");
        hideInput8.type = "hidden";
        hideInput8.name = "EndMoney"
        hideInput8.value = params.EndMoney;
        tempForm.appendChild(hideInput8);

        var hideInput9 = document.createElement("input");
        hideInput9.type = "hidden";
        hideInput9.name = "StartP"
        hideInput9.value = params.StartP;
        tempForm.appendChild(hideInput9);

        var hideInput10 = document.createElement("input");
        hideInput10.type = "hidden";
        hideInput10.name = "EndP"
        hideInput10.value = params.EndP;
        tempForm.appendChild(hideInput10);

        var hideInput11 = document.createElement("input");
        hideInput11.type = "hidden";
        hideInput11.name = "StartVoucherNo"
        hideInput11.value = params.StartVoucherNo;
        tempForm.appendChild(hideInput11);

        var hideInput12 = document.createElement("input");
        hideInput12.type = "hidden";
        hideInput12.name = "EndVoucherNo"
        hideInput12.value = params.EndVoucherNo;
        tempForm.appendChild(hideInput12);

        var hideInput13 = document.createElement("input");
        hideInput13.type = "hidden";
        hideInput13.name = "ExportType"
        hideInput13.value = "ExportAll";
        tempForm.appendChild(hideInput13);

        var hideInput14 = document.createElement("input");
        hideInput14.type = "hidden";
        hideInput14.name = "NoApproved"
        hideInput14.value = params.NoApproved;
        tempForm.appendChild(hideInput14);

        var hideInput15 = document.createElement("input");
        hideInput15.type = "hidden";
        hideInput15.name = "VG_ID"
        hideInput15.value = params.VG_ID;
        tempForm.appendChild(hideInput15);

        $(tempForm).bind("onsubmit", function () { openWindow(name); });
        document.body.appendChild(tempForm);

        tempForm.submit();
        document.body.removeChild(tempForm);
    }
    else {
        ExportSelectedItem();
    }
    $('#divExport').dialog('close');
}

function ExportSelectedItem(vid, pid) {
    var voucherIds = "";
    var voucherPIds = "";
    var printVoucherCountType = $("input[name=PrintVoucherCountType]:checked").attr("id").replace("rd", "");
    if (pid != undefined && vid != undefined) {
        voucherIds = vid;
        voucherPIds = pid;
        printVoucherCountType = "PrintSelect";
    }
    else {
        var checkBoxList = $("#divVoucherList").find(".VoucherCheck input[type=checkbox]:checked");
        if (checkBoxList.length > 0) {
            for (var i = 0; i < checkBoxList.length; i++) {
                if (voucherIds.length > 0) {
                    voucherIds += "," + $(checkBoxList[i]).attr("id");
                    voucherPIds += "," + $(checkBoxList[i]).attr("pid");
                }
                else {
                    voucherIds += $(checkBoxList[i]).attr("id");
                    voucherPIds += $(checkBoxList[i]).attr("pid");
                }
            }
        }
        else {
            global_AppMessage("提示", "亲，您还没有选择凭证哟！");
            return;
        }
    }

    var tempForm = document.createElement("form");
    tempForm.id = "tempForm1";
    tempForm.method = "post";
    tempForm.action = "Services/ExportVoucher.ashx";
    tempForm.target = "blank";

    var hideInput1 = document.createElement("input");
    hideInput1.type = "hidden";
    hideInput1.name = "VIDS"
    hideInput1.value = voucherIds;
    tempForm.appendChild(hideInput1);

    var hideInput2 = document.createElement("input");
    hideInput2.type = "hidden";
    hideInput2.name = "PS"
    hideInput2.value = voucherPIds;
    tempForm.appendChild(hideInput2);

    var hideInput3 = document.createElement("input");
    hideInput3.type = "hidden";
    hideInput3.name = "PrintVoucherCountType"
    hideInput3.value = printVoucherCountType;
    tempForm.appendChild(hideInput3);

    var hideInput4 = document.createElement("input");
    hideInput4.type = "hidden";
    hideInput4.name = "AsId"
    hideInput4.value = $("#txtAS_ID").val();
    tempForm.appendChild(hideInput4);

    var printType = $("input[name=printType]:checked").attr("id").replace("rd", "");
    var hideInput5 = document.createElement("input");
    hideInput5.type = "hidden";
    hideInput5.name = "PrintType"
    hideInput5.value = printType;
    tempForm.appendChild(hideInput5);


    var isPrintUserName = $("#cbxPrintUserName").attr("checked") ? "True" : "False";
    var hideInput6 = document.createElement("input");
    hideInput6.type = "hidden";
    hideInput6.name = "IsPrintUserName"
    hideInput6.value = isPrintUserName;
    tempForm.appendChild(hideInput6);

    var isPrintFrontCover = $("#cbxPrintFrontCover").attr("checked") ? "True" : "False";
    var hideInput7 = document.createElement("input");
    hideInput7.type = "hidden";
    hideInput7.name = "IsPrintFrontCover"
    hideInput7.value = isPrintFrontCover;
    tempForm.appendChild(hideInput7);

    var isPrintApprovedName = $("#cbxPrintApprovedName").attr("checked") ? "True" : "False";
    var hideInput8 = document.createElement("input");
    hideInput8.type = "hidden";
    hideInput8.name = "IsPrintApprovedName"
    hideInput8.value = isPrintApprovedName;
    tempForm.appendChild(hideInput8);

    var hideInput9 = document.createElement("input");
    hideInput9.type = "hidden";
    hideInput9.name = "ExportType"
    hideInput9.value = "ExportSelected";
    tempForm.appendChild(hideInput9);

    $(tempForm).bind("onsubmit", function () { openWindow(name); });
    document.body.appendChild(tempForm);

    tempForm.submit();
    document.body.removeChild(tempForm);
}

function PrintSelectedItem(vid, pid) {
    var voucherIds = "";
    var voucherPIds = "";
    var printVoucherCountType = $("input[name=PrintVoucherCountType]:checked").attr("id").replace("rd", "");
    if(pid != undefined && vid != undefined)
    {
        voucherIds = vid;
        voucherPIds = pid;
        printVoucherCountType = "PrintSelect";
    }
    else {
        var checkBoxList = $("#divVoucherList").find(".VoucherCheck input[type=checkbox]:checked");
        if (checkBoxList.length > 0) {
            for (var i = 0; i < checkBoxList.length; i++)
            {
                if (voucherIds.length > 0) {
                    voucherIds += "," + $(checkBoxList[i]).attr("id");
                    voucherPIds += "," + $(checkBoxList[i]).attr("pid");
                }
                else {
                    voucherIds += $(checkBoxList[i]).attr("id");
                    voucherPIds += $(checkBoxList[i]).attr("pid");
                }
            }
        }
        else {
            global_AppMessage("提示", "亲，您还没有选择凭证哟！");
            return;
        }
    }
    var printType = $("input[name=printType]:checked").attr("id").replace("rd", "");
    var isPrintUserName = $("#cbxPrintUserName").attr("checked") ? "True" : "False";
    var isPrintFrontCover = $("#cbxPrintFrontCover").attr("checked") ? "True" : "False";
    var isPrintApprovedName = $("#cbxPrintApprovedName").attr("checked") ? "True" : "False";
    var printDirection = $("input[name=printDirection]:checked").attr("id").replace("rdDirection", "");
    var MarginTop = $("#txtMarginTop").val();
    var MarginLeft = $("#txtMarginLeft").val();
    var exportUrl = "Services/PrintForVoucherList.ashx?VIDS=" + voucherIds
                    + "&PS=" + voucherPIds + "&PrintVoucherCountType=" + printVoucherCountType
                    + "&AsId=" + $("#txtAS_ID").val() + "&PrintType=" + printType
                    + "&IsPrintUserName=" + isPrintUserName + "&IsPrintFrontCover=" + isPrintFrontCover
                    + "&IsPrintApprovedName=" + isPrintApprovedName + "&Direction=" + printDirection
                    + "&MarginTop=" + MarginTop + "&MarginLeft=" + MarginLeft;
    window.open(exportUrl);
}
//function PrintSelectedItem(vid, pid) {
//    var voucherIds = "";
//    var voucherPIds = "";
//    var printVoucherCountType = $("input[name=PrintVoucherCountType]:checked").attr("id").replace("rd", "");
//    if (pid != undefined && vid != undefined) {
//        voucherIds = vid;
//        voucherPIds = pid;
//        printVoucherCountType = "PrintSelect";
//    }
//    else {
//        var checkBoxList = $("#divVoucherList").find(".VoucherCheck input[type=checkbox]:checked");
//        if (checkBoxList.length > 0) {
//            for (var i = 0; i < checkBoxList.length; i++) {
//                if (voucherIds.length > 0) {
//                    voucherIds += "," + $(checkBoxList[i]).attr("id");
//                    voucherPIds += "," + $(checkBoxList[i]).attr("pid");
//                }
//                else {
//                    voucherIds += $(checkBoxList[i]).attr("id");
//                    voucherPIds += $(checkBoxList[i]).attr("pid");
//                }
//            }
//        }
//        else {
//            global_AppMessage("提示", "亲，您还没有选择凭证哟！");
//            return;
//        }
//    }
//    //var printUrl = "Services/PrintForVoucherList.ashx";
//    //printUrl += "?VIDS=" + voucherIds;
//    //printUrl += "&PS=" + voucherPIds;
//    //printUrl += "&PrintVoucherCountType=" + printVoucherCountType;
//    //printUrl += "&AsId=" + $("#txtAS_ID").val();
//    //var printType = $("input[name=printType]:checked").attr("id").replace("rd", "");
//    //printUrl += "&PrintType=" + printType;
//    //var isPrintUserName = $("#cbxPrintUserName").attr("checked") ? "True" : "False";
//    //printUrl += "&IsPrintUserName=" + isPrintUserName;
//    //var isPrintFrontCover = $("#cbxPrintFrontCover").attr("checked") ? "True" : "False";
//    //printUrl += "&IsPrintFrontCover=" + isPrintFrontCover;
//    //var isPrintApprovedName = $("#cbxPrintApprovedName").attr("checked") ? "True" : "False";
//    //printUrl += "&IsPrintApprovedName=" + isPrintApprovedName;
//    //var printDirection = $("input[name=printDirection]:checked").attr("id").replace("rdDirection", "");
//    //printUrl += "&Direction=" + printDirection;

//    //var MarginTop = $("#txtMarginTop").val();
//    //var MarginLeft = $("#txtMarginLeft").val();
//    //printUrl += "&MarginTop=" + MarginTop;
//    //printUrl += "&MarginLeft=" + MarginLeft;
//    //window.open(printUrl);

//    var tempForm = document.createElement("form");
//    tempForm.id = "tempForm1";
//    tempForm.method = "post";
//    tempForm.action = "Services/PrintForVoucherList.ashx";
//    tempForm.target = "blank";

//    var hideInput1 = document.createElement("input");
//    hideInput1.type = "hidden";
//    hideInput1.name = "VIDS"
//    hideInput1.value = voucherIds;
//    tempForm.appendChild(hideInput1);

//    var hideInput2 = document.createElement("input");
//    hideInput2.type = "hidden";
//    hideInput2.name = "PS"
//    hideInput2.value = voucherPIds;
//    tempForm.appendChild(hideInput2);

//    var hideInput3 = document.createElement("input");
//    hideInput3.type = "hidden";
//    hideInput3.name = "PrintVoucherCountType"
//    hideInput3.value = printVoucherCountType;
//    tempForm.appendChild(hideInput3);

//    var hideInput4 = document.createElement("input");
//    hideInput4.type = "hidden";
//    hideInput4.name = "AsId"
//    hideInput4.value = $("#txtAS_ID").val();
//    tempForm.appendChild(hideInput4);

//    var printType = $("input[name=printType]:checked").attr("id").replace("rd", "");
//    var hideInput5 = document.createElement("input");
//    hideInput5.type = "hidden";
//    hideInput5.name = "PrintType"
//    hideInput5.value = printType;
//    tempForm.appendChild(hideInput5);


//    var isPrintUserName = $("#cbxPrintUserName").attr("checked") ? "True" : "False";
//    var hideInput6 = document.createElement("input");
//    hideInput6.type = "hidden";
//    hideInput6.name = "IsPrintUserName"
//    hideInput6.value = isPrintUserName;
//    tempForm.appendChild(hideInput6);

//    var isPrintFrontCover = $("#cbxPrintFrontCover").attr("checked") ? "True" : "False";
//    var hideInput7 = document.createElement("input");
//    hideInput7.type = "hidden";
//    hideInput7.name = "IsPrintFrontCover"
//    hideInput7.value = isPrintFrontCover;
//    tempForm.appendChild(hideInput7);

//    var isPrintApprovedName = $("#cbxPrintApprovedName").attr("checked") ? "True" : "False";
//    var hideInput8 = document.createElement("input");
//    hideInput8.type = "hidden";
//    hideInput8.name = "IsPrintApprovedName"
//    hideInput8.value = isPrintApprovedName;
//    tempForm.appendChild(hideInput8);

//    var printDirection = $("input[name=printDirection]:checked").attr("id").replace("rdDirection", "");
//    var hideInput20 = document.createElement("input");
//    hideInput20.type = "hidden";
//    hideInput20.name = "Direction"
//    hideInput20.value = printDirection;
//    tempForm.appendChild(hideInput20);

//    var MarginTop = $("#txtMarginTop").val();
//    var MarginLeft = $("#txtMarginLeft").val();

//    var hideInput21 = document.createElement("input");
//    hideInput21.type = "hidden";
//    hideInput21.name = "MarginTop"
//    hideInput21.value = MarginTop;
//    tempForm.appendChild(hideInput21);

//    var hideInput22 = document.createElement("input");
//    hideInput22.type = "hidden";
//    hideInput22.name = "MarginLeft"
//    hideInput22.value = MarginLeft;

//    tempForm.appendChild(hideInput22);

//    $(tempForm).bind("onsubmit", function () { openWindow(name); });
//    document.body.appendChild(tempForm);

//    tempForm.submit();
//    document.body.removeChild(tempForm);
//}
function PrintAllVoucher(data, name) {
    var isPrintApprovedName = $("#cbxPrintApprovedName").attr("checked") ? "True" : "False";
    var MarginTop = $("#txtMarginTop").val();
    var MarginLeft = $("#txtMarginLeft").val();
    var exportUrl = "Services/PrintForVoucherList.ashx?PageNumber=" + data.PageNumber
                    + "&PageSize=" + data.PageSize + "&AsId=" + $("#txtAS_ID").val()
                    + "&Description=" + data.Description + "&Subject=" + data.Subject
                    + "&SubjectCode=" + data.SubjectCode + "&StartMoney=" + data.StartMoney
                    + "&EndMoney=" + data.EndMoney + "&StartP=" + data.StartP
                    + "&EndP=" + data.EndP + "&PrintType=" + data.PrintType
                    + "&IsPrintUserName=" + data.IsPrintUserName + "&IsPrintFrontCover=" + data.IsPrintFrontCover
                    + "&PrintVoucherCountType=" + data.PrintVoucherCountType + "&IsPrintApprovedName=" + isPrintApprovedName
                    + "&StartVoucherNo=" + data.StartVoucherNo + "&EndVoucherNo=" + data.EndVoucherNo
                    + "&NoApproved=" + data.NoApproved + "&VG_ID=" + data.VG_ID
                    + "&Direction=" + data.Direction + "&MarginTop=" + MarginTop
                    + "&MarginLeft=" + MarginLeft;
    window.open(exportUrl);
}
//function PrintAllVoucher(data, name) {
//    var tempForm = document.createElement("form");
//    tempForm.id = "tempForm1";
//    tempForm.method = "post";
//    tempForm.action = "Services/PrintForVoucherList.ashx";
//    tempForm.target = name;

//    var hideInput1 = document.createElement("input");
//    hideInput1.type = "hidden";
//    hideInput1.name = "PageNumber"
//    hideInput1.value = data.PageNumber;
//    tempForm.appendChild(hideInput1);

//    var hideInput2 = document.createElement("input");
//    hideInput2.type = "hidden";
//    hideInput2.name = "PageSize"
//    hideInput2.value = data.PageSize;
//    tempForm.appendChild(hideInput2);

//    var hideInput3 = document.createElement("input");
//    hideInput3.type = "hidden";
//    hideInput3.name = "AsId"
//    hideInput3.value = $("#txtAS_ID").val();
//    tempForm.appendChild(hideInput3);

//    var hideInput4 = document.createElement("input");
//    hideInput4.type = "hidden";
//    hideInput4.name = "Description"
//    hideInput4.value = data.Description;
//    tempForm.appendChild(hideInput4);

//    var hideInput5 = document.createElement("input");
//    hideInput5.type = "hidden";
//    hideInput5.name = "Subject"
//    hideInput5.value = data.Subject;
//    tempForm.appendChild(hideInput5);

//    var hideInput6 = document.createElement("input");
//    hideInput6.type = "hidden";
//    hideInput6.name = "SubjectCode"
//    hideInput6.value = data.SubjectCode;
//    tempForm.appendChild(hideInput6);

//    var hideInput7 = document.createElement("input");
//    hideInput7.type = "hidden";
//    hideInput7.name = "StartMoney"
//    hideInput7.value = data.StartMoney;
//    tempForm.appendChild(hideInput7);

//    var hideInput8 = document.createElement("input");
//    hideInput8.type = "hidden";
//    hideInput8.name = "EndMoney"
//    hideInput8.value = data.EndMoney;
//    tempForm.appendChild(hideInput8);

//    var hideInput9 = document.createElement("input");
//    hideInput9.type = "hidden";
//    hideInput9.name = "StartP"
//    hideInput9.value = data.StartP;
//    tempForm.appendChild(hideInput9);

//    var hideInput10 = document.createElement("input");
//    hideInput10.type = "hidden";
//    hideInput10.name = "EndP"
//    hideInput10.value = data.EndP;
//    tempForm.appendChild(hideInput10);

//    var hideInput11 = document.createElement("input");
//    hideInput11.type = "hidden";
//    hideInput11.name = "PrintType"
//    hideInput11.value = data.PrintType;
//    tempForm.appendChild(hideInput11);

//    var hideInput12 = document.createElement("input");
//    hideInput12.type = "hidden";
//    hideInput12.name = "IsPrintUserName"
//    hideInput12.value = data.IsPrintUserName;
//    tempForm.appendChild(hideInput12);

//    var hideInput13 = document.createElement("input");
//    hideInput13.type = "hidden";
//    hideInput13.name = "IsPrintFrontCover"
//    hideInput13.value = data.IsPrintFrontCover;
//    tempForm.appendChild(hideInput13);

//    var hideInput14 = document.createElement("input");
//    hideInput14.type = "hidden";
//    hideInput14.name = "PrintVoucherCountType"
//    hideInput14.value = data.PrintVoucherCountType;
//    tempForm.appendChild(hideInput14);

//    var isPrintApprovedName = $("#cbxPrintApprovedName").attr("checked") ? "True" : "False";
//    var hideInput15 = document.createElement("input");
//    hideInput15.type = "hidden";
//    hideInput15.name = "IsPrintApprovedName"
//    hideInput15.value = isPrintApprovedName;
//    tempForm.appendChild(hideInput15);

//    var hideInput16 = document.createElement("input");
//    hideInput16.type = "hidden";
//    hideInput16.name = "StartVoucherNo"
//    hideInput16.value = data.StartVoucherNo;
//    tempForm.appendChild(hideInput16);

//    var hideInput17 = document.createElement("input");
//    hideInput17.type = "hidden";
//    hideInput17.name = "EndVoucherNo"
//    hideInput17.value = data.EndVoucherNo;
//    tempForm.appendChild(hideInput17);

//    var hideInput18 = document.createElement("input");
//    hideInput18.type = "hidden";
//    hideInput18.name = "NoApproved"
//    hideInput18.value = data.NoApproved;
//    tempForm.appendChild(hideInput18);

//    var hideInput19 = document.createElement("input");
//    hideInput19.type = "hidden";
//    hideInput19.name = "VG_ID"
//    hideInput19.value = data.VG_ID;
//    tempForm.appendChild(hideInput19);

//    var hideInput20 = document.createElement("input");
//    hideInput20.type = "hidden";
//    hideInput20.name = "Direction"
//    hideInput20.value = data.Direction;
//    tempForm.appendChild(hideInput20);

//    var MarginTop = $("#txtMarginTop").val();
//    var MarginLeft = $("#txtMarginLeft").val();

//    var hideInput21 = document.createElement("input");
//    hideInput21.type = "hidden";
//    hideInput21.name = "MarginTop"
//    hideInput21.value = MarginTop;
//    tempForm.appendChild(hideInput21);

//    var hideInput22 = document.createElement("input");
//    hideInput22.type = "hidden";
//    hideInput22.name = "MarginLeft"
//    hideInput22.value = MarginLeft;
//    tempForm.appendChild(hideInput22);

//    $(tempForm).bind("onsubmit", function () { openWindow(name); });
//    document.body.appendChild(tempForm);

//    tempForm.submit();
//    document.body.removeChild(tempForm);
//}

function openWindow(name) {
    window.open('', name);
}

var PrintType = {
    A42: "A42",
    A43: "A43",
    Invoice: "Invoice",
    A4Wide: "A4Wide"
}

var Sort = function () {
    var pId = $("#ddlSortPeroid").val();
    var vgId = $("#selectVgForSort").val();
    var sortUrl = "Services/SortVoucherNum.ashx";
    $.post(sortUrl, { SortType: "", P_ID: pId, VG_ID: vgId }, function (result) {
        if (result == "Success") {
            global_AppMessage("提示", "亲，整理成功啦！");
            SearchData(false);
            $('#divSortVoucherNo').dialog("close");
        }
        else {
            global_AppMessage("提示", "亲，整理失败了，请联系系统管理员！");
        }
    });
}

var OpenImportDialog = function () {
    $('#divImport').dialog('open');
    $('#divImport').parent().css("top", "25px");
    $('#divImport').parent().next().css("top", "25px");
    $("#divProcess div").width(0).parent().hide();
    $("#spProcess").html("").hide();
    $("#btnCancalImport").removeClass("buttonDisabled").addClass("button");
}

function ajaxFileUpload() {
    if (isImporting) {
        return;
    }
    var value = $("#myfile").attr("value");
    if (value !== "") {
        $("#divProcess").show();
        $("#spProcess").show();
        isImporting = true;
        isCanceling = false;
        $.ajaxFileUpload({
            url: '/Voucher/Services/ImportVoucher.ashx',
            type: 'post',
            secureuri: false, //一般设置为false
            fileElementId: 'myfile', // 上传文件的id、name属性名
            dataType: 'text', //返回值类型，一般设置为json、application/json
            data: { asid: $("#txtAS_ID").val(), period: $("#speriod").val() },
            success: function (returnData, status) {
                returnData = JSON.parse(returnData);
                if (returnData.result == "Success") {
                    global_AppMessage("提示", "亲，导入成功啦！");
                    $('#divImport').dialog('close');
                    EditOver(true);
                }
                else {
                    global_AppMessage("提示", returnData.ERROR);
                }
                isImporting = false;
                $("#divProcess div").width(0).parent().hide();
                $("#spProcess").html("").hide();
                $("#btnCancalImport").removeClass("buttonDisabled").addClass("button");
            },
            error: function (returnData, status, e) {
                global_AppMessage("提示", "出错了，请使用模板再次尝试！");
                isImporting = false;
                $("#divProcess div").width(0).parent().hide();
                $("#spProcess").html("").hide();
                $("#btnCancalImport").removeClass("buttonDisabled").addClass("button");
            }
        });
        GetImportStatus();
    }
    else {
        global_AppMessage("提示", "请选择文件！");
        $("#divProcess div").width(0).parent().hide();
        $("#spProcess").html("").hide().hide();
        $("#btnCancalImport").removeClass("buttonDisabled").addClass("button");
        isImporting = false;
    }
}

function GetImportStatus() {
    if (isImporting) {
        var url = "Services/GetImportProcess.ashx";
        $.ajax({
            type: "post",
            url: url,
            dateType: "text",
            success: function (result) {
                if (isCanceling) {

                }
                else {
                    switch (result) {
                        case "1010":
                            $("#divProcess div").width(40);
                            $("#spProcess").html("20%");
                            break;
                        case "1020":
                            $("#divProcess div").width(80);
                            $("#spProcess").html("40%");
                            break;
                        case "1030":
                            $("#divProcess div").width(120);
                            $("#spProcess").html("60%");
                            break;
                        case "1040":
                            $("#divProcess div").width(160);
                            $("#spProcess").html("80%");
                            $("#btnCancalImport").removeClass("button").addClass("buttonDisabled");
                            break;
                    }
                    if (result != "1040") {
                        setTimeout(GetImportStatus(), 500);
                    }
                }
            },
            error: function (data, status, e) {
                global_AppMessage("提示", "获取导入阶段失败！");
            }
        });
    }
}

function CancelImport() {
    if (isImporting) {
        if (!$("#btnCancalImport").hasClass("button")) {
            return;
        }
        var url = "Services/CancelImportVoucher.ashx";
        $.ajax({
            type: "post",
            url: url,
            dateType: "text",
            success: function (result) {
                if (result == "Success") {
                    $("#spProcess").html("正在取消，请稍候~");
                    isCanceling = true;
                }
            },
            error: function (data, status, e) {
                global_AppMessage("提示", "获取导入阶段失败！");
            }
        });
    }
    else {
        $('#divImport').dialog('close');
        $("#divProcess div").width(0).parent().hide();
        $("#spProcess").html("").hide();
        $("#btnCancalImport").removeClass("buttonDisabled").addClass("button");
    }
}

//设置cookie
function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

//读取cookies 
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}

//删除cookies 
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

function downloadTemplate() {
    var token = get_global_token();
    window.location.href = "../Voucher/Services/GetImportVocherTemp.ashx?appasid=" + token;
}

var InitVoucherUI = function (currentVNum, currentVgId, currentPId, isPrev, isNext) {
    var startVoucherNo = $("#txtVoucherNoStart").val();
    var endVoucherNo = $("#txtVoucherNoEnd").val();

    var params = {};
    params.Description = $("#txtDescription").val();
    params.Subject = $("#sbj_value_s input").attr("code");
    params.SubjectCode = $("#sbj_value_s input").attr("code");
    params.StartMoney = $("#txtMoneyStart").val();
    params.EndMoney = $("#txtMoneyEnd").val();
    params.StartP = $("#period_s").val();
    params.EndP = $("#period_e").val();
    params.StartVoucherNo = startVoucherNo;
    params.EndVoucherNo = endVoucherNo;
    params.VG_ID = $("#selectVoucherGroup").val();
    params.NoApproved = $("#noApproved").is(":checked") ? "1" : "0";
    params.CURRENT_P_ID = currentPId;
    params.CURRENT_VG_ID = currentVgId;
    params.CURRENT_V_NUM = currentVNum;
    params.IS_PREV = isPrev;
    params.IS_NEXT = isNext;
    params.IsNewVoucher = "false";

    var url = "./getSwitching.txt";
    $.post(url, params, function (result) {
        switchInfo = result;
        if (result.HasPrev) {
            $("#switchLeft").removeClass("disabledSwitchingLeft").addClass("switchingLeft");
        }
        else {
            $("#switchLeft").removeClass("switchingLeft").addClass("disabledSwitchingLeft");
        }
        if (result.HasNext) {
            $("#switchRight").removeClass("disabledSwitchingRight").addClass("switchingRight");
        }
        else {
            $("#switchRight").removeClass("switchingRight").addClass("disabledSwitchingRight");
        }

        if (result.VId != 0 && result.PId != 0) {
            EditVoucher(result.VId, result.PId, true);
        }
        else {
            isSwitching = false;
        }
    }, "json");
}

var InitVoucherUIForNew = function (currentVNum, currentVgId, currentPId, dateTime, isPrev, isNext) {
    var params = {};
    params.CURRENT_P_ID = currentPId;
    params.CURRENT_VG_ID = currentVgId;
    params.CURRENT_V_NUM = currentVNum;
    params.IS_PREV = isPrev;
    params.IS_NEXT = isNext;
    params.IsNewVoucher = "true";
    params.DateTime = dateTime;

    var url = "./getSwitching.txt";
    $.post(url, params, function (result) {
        switchInfo = result;
        if (result.HasPrev) {
            $("#switchLeft").removeClass("disabledSwitchingLeft").addClass("switchingLeft");
        }
        else {
            $("#switchLeft").removeClass("switchingLeft").addClass("disabledSwitchingLeft");
        }
        if (result.HasNext) {
            $("#switchRight").removeClass("disabledSwitchingRight").addClass("switchingRight");
        }
        else {
            $("#switchRight").removeClass("switchingRight").addClass("disabledSwitchingRight");
        }

        if (isPrev == "false" && isNext == "false") {
            $("#txtVId").val("");
            $("#txtPId").val("");
            isSwitching = false;
        }
        else {
            EditVoucher(result.VId, result.PId, true);
        }
    }, "json");
}

var ChangeButtonStatus = function () {
    if (EditType == Voucher.LoadType.EditVoucher) {
        $("#btnDeleteVoucher a").removeClass("buttonDisabled").addClass("button");
    }
    else {
        $("#btnDeleteVoucher a").removeClass("button").addClass("buttonDisabled");
    }

    if (isEditing) {
        $("#btnSaveVoucher a").removeClass("buttonDisabled").addClass("button");
    }
    else {
        $("#btnSaveVoucher a").removeClass("button").addClass("buttonDisabled");
    }
}

var ResetMarginH = function () {
    $("#txtMarginLeft").val(marginObj.left);
    $("#txtMarginRight").val(marginObj.maxH - marginObj.left);
}

var ResetMarginZ = function () {
    $("#txtMarginTop").val(marginObj.top);
    $("#txtMarginBottom").val(marginObj.maxZ - marginObj.top);
};
